#pragma once
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<functional>
#include"Log.hpp"
#include"Connection.hpp"


class HandlerConnection
{
    public:
    HandlerConnection(func_t func)
    :_func(func)
    {}
    void HanlderRecv(Connection *conn)
    {
        errno = 0;
        LOG(DEBUG,"HanlderRecv fd :%d\n",conn->Sockfd());
        while (true)
        {
            char buffer[1024];
            ssize_t n = ::recv(conn->Sockfd(),buffer,sizeof(buffer)-1,0);
            if(n>0)
            {
                buffer[n]=0;
                conn->AppendInbuffer(buffer);
            }
            else
            {
                if(errno ==EWOULDBLOCK||errno ==EAGAIN)
                {
                    break;
                }
                else if(errno == EINTR)
                {
                    continue;
                }
                else
                {
                    conn->_exceptrer(conn);
                }
            }
        }
        _func(conn);
    }
    void hanlderSend(Connection *conn)
    {
        errno = 0;
        while (true)
        {
           ssize_t n = ::send(conn->Sockfd(),conn->Outbuffer().c_str(),conn->Outbuffer().size(),0);
           if(n>0)
           {
                //n实际发送多少
                conn->OutbufferReMove(n);
                if(conn->OutbufferEmptr())
                break;
           }
           else if(n==0)
           {
                break;
           }
           else
           {
             if(errno == EWOULDBLOCK||errno==EAGAIN)
             {
                break;
             }
             else if(errno ==EINTR)
             {
                continue;
             }
             else
             {
                conn->_exceptrer(conn);
                return ;
             }
           }
        }
        if(!conn->OutbufferEmptr())
        {
            conn->_R->EnableReadWrite(conn->Sockfd(),true,true);//开启对读事件的关心
        }
        else
        {
            conn->_R->EnableReadWrite(conn->Sockfd(),true,true);
        }
    }
    void HanlderExcpet(Connection *conn)
    {
        errno = 0;
        LOG(DEBUG,"client quit : %d\n",conn->Sockfd());
        conn->_R->RemoveConnection(conn->Sockfd());
    }
    private:
    func_t _func;
};